package com.rivercloud.dao.Impl;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.rivercloud.dao.TemplateDao;
import com.rivercloud.entity.Template;

public class TemplateDaoImpl implements TemplateDao {
	static SqlSessionFactory sqlSessionFactory = null;

	static {
		SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
		InputStream inputStream = null;
		try {
			inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		sqlSessionFactory = sessionFactoryBuilder.build(inputStream);
	}

	@Override
	public List<Template> findAll() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<Template> templateList = sqlSession.selectList("findAll");

		return templateList;
	}

	@Override
	public void addTemplate(Template t) {
		SqlSession session = sqlSessionFactory.openSession();
		session.insert("addTemplate", t);

		session.commit();
		session.close();

	}

	@Override
	public int fingIdByName(String templateName) {
		SqlSession session = sqlSessionFactory.openSession();

		Template template = session.selectOne("findIdByName", templateName);
		session.close();
		return template.getId();
	}

	@Override
	public String getTemplateName(int templateId) {
		SqlSession session = sqlSessionFactory.openSession();

		Template template = session.selectOne("getTemplateName", templateId);
		session.close();
		
		return template.getTemplateName();
	}

	@Override
	public Template checkTemplateName(String templateName) {
		SqlSession session = sqlSessionFactory.openSession();

		Template template = session.selectOne("checkTemplateName", templateName);
		session.close();
		return template;
	}

	@Override
	public Template findTemplateById(int templateId) {
		SqlSession session = sqlSessionFactory.openSession();

		Template template = session.selectOne("findTemplateById", templateId);
		session.close();
		return template;
	}

	@Override
	public void addTemplateDesc(Integer templateId, String templateDesc) {
		SqlSession session = sqlSessionFactory.openSession();
		Template template = new Template();
		template.setId(templateId);
		template.setTemplateDesc(templateDesc);
		
		session.update("addTemplateDesc", template);

		session.commit();
		session.close();
		
	}

}
